import flash.net.FileReference;

var clickedId:String;
var fileRef:FileReference;
var job2Commit:Number; //jobId
var uuid2Commit:String;
var uploadFlag:Boolean;
var items:Array; //store uuids in current list
var searchObj:Object; //currentPage, totalPage, keyword
var SINGLE_PAGE:Number=8;

function init()
{
	var cont:String=Packages.system.MLF.scanDictionary(Packages.components.ReadingRecorder.recorderMain, "processResult02");
	Packages.components.ReadingRecorder.refreshResultContent(cont, false);
	var hlp:String=Packages.system.MLF.scanDictionary(Packages.components.ReadingRecorder.recorderMain, "recordHelpContent02");
	Packages.components.ReadingRecorder.refreshHelpContent(hlp);
	Packages.modula.Uploader.setResourceServerUrl();
	items=new Array();
	searchObj=new Object();
	uploadFlag=false;
	searchBook();
}

function setUuid2Commit(param:String)
{
	uuid2Commit=param;
}

function clearKeyword(param:String, data, slot:String) 
{
	var keywordInput=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "keywordInput"); 
	keywordInput.htmlText="";
}

function searchBook(param:String, data, slot:String)
{
	trace("TaskPaper.search...keyword:"+data.keyword);
	if (data.keyword==searchObj.keyword&&data.keyword!=""&&data.keyword!=null&&data.currentPage==null) 
		return;	

	var keyword=data.keyword!=null?data.keyword:"";
	if (data.currentPage==null) calcPage(keyword);
	searchObj.keyword=keyword;

	if (items.length>0)
	{
		clearItems();
		items=new Array();
	}

	var item=new Object();
	item.type="search";
	item.param=new Object();
	item.param.keyword=keyword;
	item.param.type=0;
	item.param.index=(searchObj.currentPage-1)*SINGLE_PAGE;
	item.param.length=SINGLE_PAGE;
	item.result=new Object();
	item.result.owner=this;
	//for (var a in item.param) trace("item.param."+a+":"+item.param[a]);
	item.result.onResult=function(res)
	{
		trace("search.onResult.obj.returnObj: "+res.returnObj.length);
		for (var a=0; a<res.returnObj.length; a++)
		{
			var rObj:Object=new Object();
			rObj.type="book";
			rObj.content=new Object();
			rObj.content.id=Packages.system.Util.minus2Under(res.returnObj[a].uuid);
			rObj.content.bookName=res.returnObj[a].name;
			rObj.content.authorName=res.returnObj[a].author;
			addItem(rObj);
		}
	}	
	Packages.system.MLF.rtmpCaller(item);
}

function displayItemPortlet(cont:String)
{
	mlf.gatekeeper.native.Caller.MLoader(null, null, null, null, cont);
}

function clickItem(param:String, data, slot:String)
{
	//trace("clickItem.param..."+param);
	var id=param.substring(param.indexOf("bookBg_")+7);
	var bg=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookBg_"+id);
	bg._alpha=100;
	Packages.system.Platform.highlightBlock(bg);

	if (clickedId!=null&&clickedId!=id)
	{
		bg=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookBg_"+clickedId);
		bg._alpha=0;
	}
	clickedId=id;

	// save into the Packages.task.Composition.contentId
	Packages.task.Composition.contentId=Packages.system.Util.getHttpBaseUrl()+"/download?uuid="+Packages.system.Util.under2Minus(id)+"&type=0";
	trace("Packages.task.Composition.contentId: "+Packages.task.Composition.contentId);
	// refreshResultContent
	var bookName=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookName_"+id).text;
	var cont:String=Packages.system.MLF.scanDictionary(Packages.components.ReadingRecorder.recorderMain, "processResult03")+bookName+Packages.system.MLF.scanDictionary(Packages.components.ReadingRecorder.recorderMain, "processResult04");
	Packages.components.ReadingRecorder.refreshResultContent(cont, true);
}

function traceItem(param:Object)
{
	//Display a file upload process
	var fileName=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "fileName");
	fileName.htmlText=param.item.name;
	var stat=Packages.system.MLF.scanDictionary(fileName, param.stat);
	var flag="hint";
	if (param.stat.indexOf("Error")>-1)
	{
		flag="warning";
	}
	Packages.system.Platform.messageHint("ReadingRecorder", stat, flag);	// hint cloud message center
}

function addItem(item:Object)
{
	//Add an uploaded resource into Book List
	items.push(item.content.id);
	if (item.type=="book")
	{
		displayItemPortlet(Packages.modula.ReadingQuery.getBookItem(item.content));
	}
}

function clearItems()
{
	var itemStr=items.pop();
	while (itemStr!=null)
	{
		trace("itemStr:"+itemStr);
		var item=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookItem_"+itemStr);
		if (item!=null) 
		{
			item.unloadMovie();
			item.removeMovieClip();	
			mlf.mcmanager.component.IndexSlot.removeElement("TaskPaper", "bookItem_"+itemStr); 
		}
		itemStr=items.pop();
	}
	//items=new Array();
}

function calcPage(keyword:String)
{
	//trace("keyword:"+keyword+"---searchObj.keyword:"+searchObj.keyword);
	if (keyword!=searchObj.keyword||searchObj.totalPage==null)
	{
		var item=new Object();
		item.type="count";
		item.param=new Object();
		item.param.keyword=keyword!=null?keyword:"";
		item.param.type=0;
		item.result=new Object();
		item.result.owner=this;
		for (var a in item.param) trace("item.param."+a+":"+item.param[a]);
		item.result.onResult=function(res)
		{
			trace("count.onResult.obj.returnObj: "+res.returnObj);
			//this.owner.clearItems();
			if (res.returnObj!=null)
			{
				var totalPage=Math.ceil(res.returnObj/SINGLE_PAGE);
				searchObj.totalPage=totalPage;
				var tp=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "totalPage");
				tp.htmlText=searchObj.totalPage;
			}
		}	
		Packages.system.MLF.rtmpCaller(item);	
		
		searchObj.currentPage=1;
		var cp=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "currentPage");
		cp.htmlText=searchObj.currentPage;
	}
}

function nextPage()
{
	//trace("nextPage..");
	if (searchObj.currentPage+1<=searchObj.totalPage)
	{ 	
		searchObj.currentPage++;
		searchBook(null, searchObj, null);
		var cp=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "currentPage");
		cp.htmlText=searchObj.currentPage;	
	}
}

function prevPage()
{
	//trace("prevPage..");
	if (searchObj.currentPage>1) 
	{
		searchObj.currentPage--;
		searchBook(null, searchObj, null);
		var cp=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "currentPage");
		cp.htmlText=searchObj.currentPage;	
	}
}

function firstPage()
{
	//trace("firstPage..");
	if (searchObj.currentPage!=1)
	{
		searchObj.currentPage=1;
		searchBook(null, searchObj, null);
		var cp=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "currentPage");
		cp.htmlText=searchObj.currentPage;	
	}
}

function lastPage()
{
	//trace("lastPage..");
	if (searchObj.currentPage!=searchObj.totalPage)
	{
		searchObj.currentPage=searchObj.totalPage;
		searchBook(null, searchObj, null);
		var cp=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "currentPage");
		cp.htmlText=searchObj.currentPage;	
	}
}

function setFocusTextField()
{
	Selection.setFocus(mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookNameInput"));
}

function openFileDialog()
{
	var bookName=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookNameInput");
	var bookAuthor=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "authorNameInput");
	/*
	// If book name & author already set
	var bookName=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookNameInput");
	var bookAuthor=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "authorNameInput");
	if (uploadFlag==true||bookName.htmlText==""||bookAuthor.htmlText=="")
	{
		trace("uploadFlag:"+uploadFlag+" bookName:"+bookName.htmlText+" bookAuthor:"+bookAuthor.htmlText);
		/*var uploadStatus=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "uploadStatus");
		uploadStatus.htmlText="Please fill book name&author.";*?
		var invokeObj=new Object();
		invokeObj.path=mlf.mcmanager.PathResolver.drawPath(this);
		invokeObj.func="setFocusTextField";
		invokeObj.args=new Array();
		var hintMessage=Packages.system.MLF.scanDictionary(bookName, "fillNameHint");
		Packages.system.Platform.messageHint("ReadingRecorder", hintMessage, "warning", invokeObj);	// hint cloud message center
		return;
	}
	*/
	
	uploadFlag=true;
	fileRef=new FileReference();
	var listener:Object = new Object();
	listener.owner = this;
	listener.onSelect = function(file:FileReference) {
		//trace("onSelect ...");
		var obj:Object = new Object();
		obj.item = file;
		obj.date = Packages.system.Util.getTimestamp();
		var offset:Number = Math.floor(Math.random()*1000000)+1000000;
		obj.jobId = offset+obj.date;
		//trace("jobId:"+obj.jobId+"...offset:"+offset+"...date:"+obj.date);
		obj.stat = "waiting";
		if (Packages.modula.Uploader.addFileToUploadQueue(obj)) {
			file.addListener(this);
			if (obj.item.name != null && obj.item.name != "") {
				traceItem(obj);
			}
			job2Commit=obj.jobId;

			var uuid:String;
			var item=new Object();
			item.type="generateUuid";
			item.param=new Object();
			item.result=new Object();
			item.result.owner=this;
			item.result.onResult=function(res)
			{
				trace("onResult.obj.returnObj: "+res.returnObj);
				obj.uuid=res.returnObj;
				obj.bookName=bookName.htmlText;
				obj.bookAuthor=bookAuthor.htmlText;
				this.owner.owner.uploadResource(obj);
				this.owner.owner.setUuid2Commit(res.returnObj);
			}	
			Packages.system.MLF.rtmpCaller(item);
		}
	};

	listener.onCancel = function(file:FileReference):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "onCancel";
		file.removeListener(this);
		uploadFlag=false;
	};

	listener.onOpen = function(file:FileReference):Void  {
		//trace("onOpen ...");
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "onOpen";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
	};

	listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void  {
		var progress:String = Math.floor(bytesLoaded/bytesTotal*100)+"%";
		//trace("onProgress ... "+progress);
		var obj:Object = new Object();
		obj.item = file;
		var content=Packages.system.MLF.scanDictionary(mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "uploadPart"), "Upload Progress");
		obj.stat = content+progress;
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
	};

	listener.onComplete = function(file:FileReference):Void  {
		//trace("onComplete ...");
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "completed";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
		file.removeListener(listener);
		uploadFlag=false;
		commitResource(uuid2Commit, bookName.htmlText, bookAuthor.htmlText);
		bookName.htmlText="";
		bookAuthor.htmlText="";
	};

	listener.onHTTPError = function(file:FileReference, httpError:Number):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "httpError";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
		file.removeListener(listener);
	};

	listener.onIOError = function(file:FileReference):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "IoError";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
		file.removeListener(listener);
	};

	listener.onSecurityError = function(file:FileReference, errorString:String):Void  {
		var obj:Object = new Object();
		obj.item = file;
		obj.stat = "securityError";
		if (obj.item.name != null && obj.item.name != "") {
			traceItem(obj);
		}
		file.removeListener(listener);
	};

	fileRef.addListener(listener);
	var fileTypes:Array=[{description:"Text", extension:"*.txt"}];
	fileRef.browse(fileTypes);
}

function uploadResource(element:Object)
{
	trace("uploadResource...");
	var jobId:String = element.jobId;
	var file:FileReference = element.item;
	var stat:String = element.stat;
	if (file == undefined) {
		return;
	}

	if (file.size>900000000) {
		trace("The file is too big to upload!");
		file.removeListener();
		return;
	}

	if (stat != "waiting") {
		return;
	}

	element.mimeType = "text/plain";
	element.stat = "uploading";
	var fileName:Array = file.name.split(file.type);
	element.fileName = fileName[0];
	//var url = Packages.modula.Uploader.getResourceUploadUrl()+
	//	"?creator="+"testCreator"+"&suffix="+file.type+"&mimeType="+element.mimeType+
	//	"&sourcename="+file.name+"&jobId="+jobId+"&sessionId="+"testSessionId";
	var url = Packages.modula.Uploader.getResourceUploadUrl()+
		"?creator="+"testCreator"+"&suffix="+file.type+"&mimeType="+element.mimeType+
		"&bookName="+element.bookName+"&bookAuthor="+element.bookAuthor+"&sessionId="+"testSessionId"+
		"&uuid="+element.uuid+"&type=0";
	file.upload(url);
	trace(url);
}

function commitResource(uuid:String, bookName:String, authorName:String)
{
	//trace("commitResource...uuid:"+uuid+" bookName:"+bookName+" authorName:"+authorName);
	if (uuid=="" || bookName=="" || authorName=="")
	{
		trace("Incomplete book information!");
		return;
	}
	
	var element=Packages.modula.Uploader.delFileFromUploadQueue(job2Commit);
	if (element!=null)
	{
		//trace("addItem...id:"+element.jobId);
		var item:Object=new Object();
		item.type="book";
		item.content=new Object();
		item.content.bookName=bookName;
		item.content.authorName=authorName;
		item.content.id=Packages.system.Util.minus2Under(uuid);
		addItem(item);
	}

	var item=new Object();
	item.type="saveBook";
	item.param=new Object();
	item.param.uuid=uuid;
	item.param.bookName=bookName;
	item.param.bookAuthor=authorName;
	item.result=new Object();
	item.result.owner=this;
	//for (var a in item.param) trace("item.param."+a+":"+item.param[a]);
	item.result.onResult=function(res)
	{
		trace("saveBook.onResult.obj.returnCode: "+res.returnCode);
	}	
	Packages.system.MLF.rtmpCaller(item);
}

function rolloutCon(param, data, slot)
{
	mlf.mcmanager.PathResolver.extractPath(param+"Bg")._visible=true;
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg"), 0);
}

function rolloverCon(param, data, slot)
{
	// trace("rolloverCon.uploadFlag: "+uploadFlag);
	var bookName=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookNameInput");
	var bookAuthor=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "authorNameInput");
	if (bookName.text=="" || bookAuthor.text=="" || uploadFlag)
	{
		return;
	}
	mlf.mcmanager.PathResolver.extractPath(param+"Bg")._visible=false;
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg"), 50);
}

function pressCon(param, data, slot)
{
	var bookName=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookNameInput");
	var bookAuthor=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "authorNameInput");
	if (bookName.text=="" || bookAuthor.text=="")
	{
		var invokeObj=new Object();
		invokeObj.path=mlf.mcmanager.PathResolver.drawPath(this);
		invokeObj.func="setFocusTextField";
		invokeObj.args=new Array();
		var hintMessage=Packages.system.MLF.scanDictionary(bookName, "fillNameHint");
		Packages.system.Platform.messageHint("ReadingRecorder", hintMessage, "warning", invokeObj);	// hint cloud message center
		return;
	}
	else if (uploadFlag)
	{
		var hintMessage=Packages.system.MLF.scanDictionary(bookName, "uploadingHint");
		Packages.system.Platform.messageHint("ReadingRecorder", hintMessage, "warning");	// hint cloud message center
		return;
	}
	Packages.system.Platform.highlightBG(mlf.mcmanager.PathResolver.extractPath(param), mlf.gatekeeper.native.Caller.scanElement(slot, "highlightBg"), 100);
}

function releaseCon(param, data, slot)
{
	var bookName=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "bookNameInput");
	var bookAuthor=mlf.gatekeeper.native.Caller.scanElement("TaskPaper", "authorNameInput");
	if (bookName.text=="" || bookAuthor.text=="" || uploadFlag)
	{
		return;
	}
	rolloutCon(param, data, slot);
	openFileDialog();
}